import React, {useEffect, useRef} from 'react';
import {SecurityMenu} from "../../type/SecurityMenu";
import {Select ,Form} from "antd";
import {DefaultOptionType} from "rc-select/lib/Select";
import {requestGet} from "../../util/request";
import {FormInstance} from "antd/lib";

interface SelectEnhanceProps<T> {
    /**
     * 表单的实例
     */
    form: FormInstance<T>,
    /**
     * 当表单的Select变化时，需要设置的表单字段的key
     */
    rowKey: keyof T,
    /**
     * 选择的字段的名字
     */
    selectName: keyof T ,
    /**
     * 选择的字段的标签
     */
    selectLabel: string ,
}

const SelectEnhance = <T,> (props: SelectEnhanceProps<T>) => {
    const [option , setOption] = React.useState<DefaultOptionType[]>([]) ;
    const parentRef = useRef<SecurityMenu[]>([]) ;
    const [loading, setLoading] = React.useState<boolean>(true) ;
    useEffect(() => {
        requestGet<SecurityMenu[]>("/manager/security-menu/parent")
            .then(res => {
                parentRef.current = res.data ;
                setOption(res.data.map((item) => ({ label: item.label, value: item.id }))) ;
                setLoading(false);
            }) ;
    }, []);
    const selectOnChange = (value: number) => {
        // log.debug("选择父菜单: " , value) ;
        props.form.setFieldValue(props.rowKey, parentRef.current.find(e => e.id === value)?.path) ;

    };
    return (
        <>
            <Form.Item label={props.selectLabel} name={props.selectName as string}>
                <Select
                    loading={loading}
                    options={option}
                    maxLength={3}
                    onChange={ selectOnChange }
                />
            </Form.Item>
        </>
    );
};

export default SelectEnhance;